package org.ohuang;


import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.util.Base64;

public class DataDecode {

    public static String g_str_config_password="6461772803150152";//云端数据AES解密用密码
    public static String g_str_config_iv="uieewu#duieewu#d";//云端数据AES解密用iv

    /**
     * 解密
     * @param encrypted
     * @param keyStr
     * @param ivStr
     * @return
     */
    public static String fn_AES_decode(String encrypted, String keyStr, String ivStr)
    {
        try

        {

            Base64.Decoder decoder = Base64.getDecoder();
            byte[] encryptedBytes= decoder.decode(encrypted.getBytes());
            Key key = new SecretKeySpec(keyStr.getBytes(), "AES");
            AlgorithmParameters iv=AlgorithmParameters.getInstance("AES");
            iv.init(new IvParameterSpec(ivStr.getBytes()));
            Cipher cipher= Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, iv);
            return new String(cipher.doFinal(encryptedBytes));
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 加密
     * @param encrypted
     * @param keyStr
     * @param ivStr
     * @return
     */
    public static String fn_AES_encode(String encrypted, String keyStr, String ivStr){
        try

        {


            Key key = new SecretKeySpec(keyStr.getBytes(), "AES");
            AlgorithmParameters iv=AlgorithmParameters.getInstance("AES");
            iv.init(new IvParameterSpec(ivStr.getBytes()));
            Cipher cipher= Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key, iv);
            byte[] bytes = cipher.doFinal(encrypted.getBytes());
            Base64.Encoder decoder = Base64.getEncoder();
            byte[] encryptedBytes= decoder.encode(bytes);
            return new String(encryptedBytes);
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return "";
        }
    }

}
